import type { ApplicationAddRequest, ApplicationList } from "@/pages/internship/application/appliction-student/apis/type"
import type { ResumeSimple } from "@/pages/internship/resume/apis/type"
import { defineStore } from "pinia"
import { ref } from "vue"
import { createApplicationApi, getUserApplicationsApi } from "@/pages/internship/application/appliction-student/apis"
import { getUserResumesSamlApi } from "@/pages/internship/resume/apis"
import { pinia } from "@/pinia"
import { useUserStore } from "./user"

export const useApplicationStore = defineStore("application", () => {
  // 申请状态
  const isSubmitting = ref(false)
  const submitSuccess = ref(false)
  const submitError = ref<string | null>(null)

  // 简历相关状态
  const userResumes = ref<ResumeSimple[]>([])
  const selectedResume = ref<ResumeSimple | null>(null)
  const isResumeDialogVisible = ref(false)
  const isLoadingResumes = ref(false)

  // 申请列表相关状态
  const userApplications = ref<ApplicationList[]>([])
  const isLoadingApplications = ref(false)
  const applicationsError = ref<string | null>(null)

  // 获取用户简历列表
  const fetchUserResumes = async () => {
    const userStore = useUserStore()
    const userId = userStore.userInfo?.userId

    if (!userId) {
      console.error("用户ID不存在")
      return []
    }

    isLoadingResumes.value = true
    try {
      const response = await getUserResumesSamlApi(userId)
      if (response && response.data) {
        userResumes.value = response.data
        // 设置默认简历
        const defaultResume = response.data.find(resume => resume.isDefault === 1)
        selectedResume.value = defaultResume || response.data[0] || null
        return response.data
      }
      return []
    } catch (error) {
      console.error("获取用户简历失败:", error)
      return []
    } finally {
      isLoadingResumes.value = false
    }
  }

  // 选择简历
  const selectResume = (resume: ResumeSimple) => {
    selectedResume.value = resume
  }

  // 打开简历选择对话框
  const openResumeDialog = async () => {
    if (userResumes.value.length === 0) {
      await fetchUserResumes()
    }
    isResumeDialogVisible.value = true
  }

  // 关闭简历选择对话框
  const closeResumeDialog = () => {
    isResumeDialogVisible.value = false
  }

  // 申请职位方法
  const applyPosition = async (applicationData: ApplicationAddRequest) => {
    isSubmitting.value = true
    submitSuccess.value = false
    submitError.value = null

    try {
      const response = await createApplicationApi(applicationData)

      if (response && response.data) {
        submitSuccess.value = true
        return true
      } else {
        submitError.value = "申请失败，请稍后重试"
        return false
      }
    } catch (error: any) {
      console.error("申请职位失败:", error)
      submitError.value = error.message || "申请失败，请检查网络连接"
      return false
    } finally {
      isSubmitting.value = false
    }
  }

  // 重置提交状态
  const resetSubmitStatus = () => {
    submitSuccess.value = false
    submitError.value = null
  }

  // 获取用户申请列表
  const fetchUserApplications = async () => {
    const userStore = useUserStore()
    const userId = userStore.userInfo?.userId

    if (!userId) {
      console.error("用户ID不存在")
      applicationsError.value = "用户ID不存在"
      return []
    }

    isLoadingApplications.value = true
    applicationsError.value = null

    try {
      const response = await getUserApplicationsApi(userId)
      if (response && response.data) {
        userApplications.value = response.data
        return response.data
      }
      return []
    } catch (error: any) {
      console.error("获取用户申请列表失败:", error)
      applicationsError.value = error.message || "获取申请列表失败"
      return []
    } finally {
      isLoadingApplications.value = false
    }
  }

  // 重置申请列表状态
  const resetApplicationsStatus = () => {
    userApplications.value = []
    isLoadingApplications.value = false
    applicationsError.value = null
  }

  return {
    // 状态
    isSubmitting,
    submitSuccess,
    submitError,
    userResumes,
    selectedResume,
    isResumeDialogVisible,
    isLoadingResumes,
    userApplications,
    isLoadingApplications,
    applicationsError,
    // 方法
    applyPosition,
    resetSubmitStatus,
    fetchUserResumes,
    selectResume,
    openResumeDialog,
    closeResumeDialog,
    fetchUserApplications,
    resetApplicationsStatus
  }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function useApplicationStoreOutside() {
  return useApplicationStore(pinia)
}
